import 'dart:convert';
import 'dart:math';

import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:vape_xe/routes/app_pages.dart';
import 'package:vape_xe/services/services.dart';
import 'package:vape_xe/utils/utils.dart';
import 'package:vape_xe/values/values.dart';
import 'package:vape_xe/widgets/widgets.dart';

class ProfileController extends GetxController with GetSingleTickerProviderStateMixin {
  /// 响应式成员变量
  final _profileData = <String, dynamic>{}.obs;

  set profileData(value) => _profileData.value = value;

  get profileData => _profileData.value;

  final _showProgress = true.obs;

  set showProgress(value) => _showProgress.value = value;

  get showProgress => _showProgress.value;

  final _progressValue = .0.obs;

  set progressValue(value) => _progressValue.value = value;

  double get progressValue => _progressValue.value;

  /// 成员变量
  late AnimationController _animationController;
  late Animation<double> _progressAnimation;

  /// 事件
  void logout() {
    Get.dialog(DialogView(
      message: 'Are you sure to sign out?'.tr,
      onCancelEvent: () {},
      onConfirmEvent: () async {
        await UserStore.to.onLogout();
        Get.offAllNamed(Routes.SIGN_IN);
      },
    ));
  }

  void _startAnimation(double target) {
    if (target == 0.0) {
      // 进度为0，直接赋值
      progressValue = target;
      return;
    }
    _animationController.animateTo(min(1.0, target));
  }

  /// 生命周期
  @override
  void onInit() {
    super.onInit();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 600),
    );
    _progressAnimation =
        Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(parent: _animationController, curve: Curves.linear))
          ..addListener(() {
            progressValue = _progressAnimation.value * 100;
          });

    var profileDataOffline = StorageService.to.getString(STORAGE_PROFILE_INFO);
    if (profileDataOffline.isNotEmpty) {
      showProgress = false;
      profileData = jsonDecode(profileDataOffline);
      _startAnimation((profileData['levelData']['experience'] - profileData['levelData']['nowLevelExp']) /
          (profileData['levelData']['nextLevelExp'] - profileData['levelData']['nowLevelExp']));
    }

    ever(EventService.to.message, (message) async {
      if (message.startsWith('${EventService.EventUpdate}_${EventService.ModuleNickname}')) {
        profileData['nickName'] = message.substringAfter('${EventService.EventUpdate}_${EventService.ModuleNickname}_');
        _profileData.refresh();
        StorageService.to.setString(STORAGE_PROFILE_INFO, jsonEncode(profileData));
      }
    });
  }

  @override
  void onReady() async {
    super.onReady();
    await Request().get('/user/userData').then((result) {
      showProgress = false;
      profileData = result['result'];
      StorageService.to.setString(STORAGE_PROFILE_INFO, jsonEncode(result['result']));
      _startAnimation((profileData['levelData']['experience'] - profileData['levelData']['nowLevelExp']) /
          (profileData['levelData']['nextLevelExp'] - profileData['levelData']['nowLevelExp']));
    });
  }
}
